/**
 * 用户管理
 */
const router = require('koa-router')()
const Dept = require('../models/deptSchema')
const util = require('../utils/util')
const jwt = require('jsonwebtoken')
const log4js = require('../utils/log4j')
const md5 = require('md5')

router.prefix('/depts')

router.get('/list', async ctx => {
  try {
    const { deptName } = ctx.request.query;
    const params = {};
    if (deptName) {
      params.deptName = new RegExp(deptName, 'i');
      let rootList = await Dept.find(params);
      ctx.body = util.success(rootList);
      return
    }
    let rootList = await Dept.find(params);
    rootList = getTreeDept(rootList, null, []);
    ctx.body = util.success(rootList);
  } catch (error) {
    ctx.body = util.fail(error.stack);
  }
})

const getTreeDept = (source, id, list) => {
  for (const item of source) {
    if (String(item.parentId.slice().pop()) == String(id)) {
      list.push(item._doc);
    }
  }
  list.forEach(item => {
    item.children = [];
    getTreeDept(source, item._id, item.children);
    if (item.children.length === 0) {
      delete item.children;
    }
  })
  return list
}

router.post('/operate', async ctx => {
  try {
    const { _id, action, ...params } = ctx.request.body;
    let res, info;
    if (action === 'add') {
      res = await Dept.create(params)
      info = '创建成功'
    } else if (action === 'edit') {
      params.updateTime = Date.now();
      delete params._id;
      res = await Dept.findByIdAndUpdate(_id, params);
      info = '修改成功'
    } else if (action === 'delete') {
      res = await Dept.findByIdAndDelete(_id)
      await Dept.deleteMany({ parentId: { $all: [_id] } })
      info = '删除成功'
    }
    ctx.body = util.success(res, info);
  } catch (error) {
    ctx.body = util.fail(error.stack);
  }
})

module.exports = router;
